package com.yugao.fintech.draper.core.util;

import cn.hutool.core.collection.CollectionUtil;
import com.yugao.fintech.draper.core.model.TreeNode;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@UtilityClass
public class TreeUtil {
    /**
     * 顶级节点 ID
     */
    private final static String TOP_NODE_ID = "0";

    /**
     * 构建树形VueRouter
     *
     * @param routes routes
     * @return 树形VueRouter
     */
    public static <T> List<TreeNode<T>> buildVueRouter(List<TreeNode<T>> routes) {
        if (CollectionUtil.isEmpty(routes)) {
            return null;
        }

        List<TreeNode<T>> topRoutes = new ArrayList<>();
        Map<String, TreeNode<T>> routerMap = routes.stream()
                .collect(Collectors.toMap(TreeNode::getId, Function.identity()));

        routes.forEach(route -> {
            String parentId = route.getParentId();
            if (TOP_NODE_ID.equals(parentId)) {
                topRoutes.add(route);
            } else {
                TreeNode<T> parent = routerMap.get(parentId);
                if (Objects.isNull(parent)) {
                    return;
                }

                if (CollectionUtil.isEmpty(parent.getChildren())) {
                    parent.initChildren();
                }

                parent.getChildren().add(route);
                parent.setAlwaysShow(true);
                parent.setHasChildren(true);
                route.setHasParent(true);
                parent.setHasParent(true);
            }
        });

        return topRoutes;
    }
}